Fix typechecking for async generators #17452
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #10534
This PR fixes a bug in typechecking asynchronous generators.
Mypy currently typechecks a generator/comprehension as
AsyncGenerator
if the leftmost expression containsawait
, or if it contains anasync for
.However, there are other situations where we should get async generator: If there is an
await
expression in any of the conditions or in any sequence except for the leftmost one, the generator/comprehension should also be typechecked asAsyncGenerator
.I've implemented this change in Mypy and added a test case to assert this behavior. If I enter the test cases into a regular repl, I can confirm that the runtime representation is generator/async_generator as the test case expects.
According to the language reference:
Confusingly, the documentation itself is actually not quite correct either, as pointed out in python/cpython#114104
Alongside this change, I've made a PR to update the docs to be more precise: python/cpython#121175 has more details.